import pathlib
import subprocess

import docx
from docx import Document
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.shared import Pt

from Common.CommonUtils import CommonUtils


class WordWrite:
    """word文档读写"""

    def __init__(self, file_path, CounselorInformation, coordinatorPath):

        # 打开Word文档
        self.file_path = file_path

        self.doc = None

        # 辅导员的信息
        self.CounselorInformation = CounselorInformation

        # 班主任的文件路径信息
        self.coordinatorPath = coordinatorPath

        # 定义要替换的内容和新内容
        self.replacements = {
            '#grade': '人工智能22-6',
            '#studentId': '123456',
            '#allcredits': '75',
            '#name': '人才',
            "#SemesterTime_start": "",
            "#SemesterTime_shop": "",
            "#middle": "",
            "#disciplinesNum": "",
            "#table": "",
            "#date": "",
            "#CounselorInformation": self.CounselorInformation,

        }

        self.allDisciplinesNum = []

    def write(self, personList):
        CommonUtils.set_information("开始写入文档")
        name = ""
        for person in personList:
            name = person.get_name()
            grade = person.get_grade()
            self.replacements["#grade"] = grade
            self.replacements["#studentId"] = person.get_studentId()
            self.replacements["#allcredits"] = person.get_allCredits()
            self.replacements["#SemesterTime_start"] = person.SemesterTime_start
            self.replacements["#SemesterTime_shop"] = person.SemesterTime_shop
            self.replacements["#middle"] = person.middle
            self.replacements["#disciplinesNum"] = person.disciplinesNum
            self.replacements["#name"] = name

            file_name = '预警通知书打印件' if "打印" in self.file_path else "预警通知书"
            save_path = pathlib.Path.home() / "Desktop" / file_name / grade
            # 检查目录是否存在
            if not save_path.exists():
                # 如果不存在，创建目录
                save_path.mkdir(parents=True)
            save_path = save_path / f"{name}-{file_name}.docx"

            # 使用函数替换文档内容
            self.replace_multiple_contents_in_word(str(save_path), self.replacements, person.get_allDisciplinesNum())
            CommonUtils.set_information(f"{name}-预警警告书编写完成并保存")

    # 编写文档
    def replace_multiple_contents_in_word(self, save_path, replacements, allDisciplinesNum):

        # 打开Word文档
        try:
            self.doc = Document(self.file_path)
        except:
            CommonUtils.set_information("文档打开有问题！！！ \n请重新选择")
        # 遍历文档中的所有段落
        i = 0
        # 记录要插入表格的位置
        paragraphs = set()
        coordinator = ""
        for paragraph in self.doc.paragraphs:
            # print("第" + str(i) + paragraph.text)
            # 表格插入的段络
            i += 1
            # 遍历要替换的内容字典
            for old_text, new_text in replacements.items():
                # 检查当前段落是否包含要替换的文本
                if "#table" in paragraph.text:
                    paragraphs.add(i)
                if old_text in paragraph.text:

                    # 替换文本并更新段落
                    if old_text == "#grade":
                        coordinator = self.write_coordinator(new_text)
                        # print(coordinator + "," + old_text)
                    if old_text == "#date":
                        paragraph.text = paragraph.text.replace(old_text, CommonUtils.get_date())

                    paragraph.text = paragraph.text.replace(old_text, new_text)
                paragraph.text = paragraph.text.replace("#coordinator", coordinator)

        self.InsertTable(paragraphs, allDisciplinesNum)

        # 保存修改后的文档
        self.doc.save(save_path)


    def InsertTable(self, paragraphs, allDisciplinesNum):

        # 插入表格
        for i in paragraphs:
            paragraph = self.doc.paragraphs[i]
            table = self.doc.add_table(rows=len(allDisciplinesNum) + 1, cols=3)

            # 获取表格的第一个单元格
            cell = table.cell(0, 0)
            cell.text = '课程名称'
            cell = table.cell(0, 1)
            cell.text = '成绩'
            cell = table.cell(0, 2)
            cell.text = '学分'

            cell_row = 1
            for disciplines in allDisciplinesNum:
                table.cell(cell_row, 0).text = disciplines.get_subjectName()
                table.cell(cell_row, 1).text = disciplines.get_subjectGrades()
                table.cell(cell_row, 2).text = disciplines.get_subjectCredit()
                cell_row += 1

            # 设置表格样式
            table.style = 'Table Grid'
            self.tablePattern(table)

            # 将新表格插入到指定段落前面
            self.move_table_after(table, paragraph)
            # 插入换页符
            if i < max(paragraphs):
                self.doc.paragraphs[i + 1].runs[0].add_break(docx.enum.text.WD_BREAK.PAGE)

    # 移动表后
    def move_table_after(self, table, paragraph):
        tbl, p = table._tbl, paragraph._p
        p.addnext(tbl)

    # 表格的内部样式
    def tablePattern(self, table):
        for row in table.rows:
            for cell in row.cells:
                for paragraph in cell.paragraphs:
                    paragraph.paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER

            # 设置表格中的字体大小
        for row in table.rows:
            for cell in row.cells:
                for paragraph in cell.paragraphs:
                    for run in paragraph.runs:
                        run.font.size = Pt(10.5)  # 设置字体大小为12磅

    # 写入班主任信息
    def write_coordinator(self, grade):

        if self.coordinatorPath == "":
            CommonUtils.set_information("联系方式未加载")
            return
        rows_data = CommonUtils.table_extract(self.coordinatorPath)
        for i, row in enumerate(rows_data):
            if row[2] == grade and i != 0:
                input_string = str(row[1])
                if "." in input_string:
                    return input_string.split(".")[0]
                else:
                    return input_string
        return " "
